<template>
  <div class="order-container">
    <PageHeader title="我的订单" :show-back="false" />

    <div class="order-tabs">
      <van-tabs v-model:active="activeTab" sticky>
        <van-tab title="全部" name="all"></van-tab>
        <van-tab title="待付款" name="待付款"></van-tab>
        <van-tab title="待发货" name="待发货"></van-tab>
        <van-tab title="待收货" name="待收货/已发货"></van-tab>
        <van-tab title="已完成" name="已完成"></van-tab>
        <van-tab title="已取消" name="已取消"></van-tab>
      </van-tabs>
    </div>

    <div class="order-list">
      <!-- 加载中 -->
      <div v-if="loading" class="loading-container">
        <van-loading type="spinner" />
      </div>

      <!-- 空状态 -->
      <div v-else-if="orderList.length === 0" class="empty-container">
        <van-empty description="暂无订单" />
      </div>

      <!-- 订单列表 -->
      <div v-else>
        <div class="order-item" v-for="order in orderList" :key="order.id">
          <div class="order-header">
            <div class="order-no">订单号：{{ order.orderNo }}</div>
            <div class="order-status">{{ order.status }}</div>
          </div>
          <div class="order-content" @click="goToOrderDetail(order.id)">
            <div class="product-item" v-for="(item, index) in order.items" :key="index">
              <img
                :src="item.product?.image || item.image"
                :alt="item.productName"
                class="product-img"
              />
              <div class="product-info">
                <div class="product-name">{{ item.productName }}</div>
                <div class="product-price">{{ item.points }} 积分</div>
                <div class="product-quantity">x{{ item.quantity }}</div>
              </div>
            </div>
          </div>
          <div class="order-footer">
            <div class="order-total">
              共{{ order.items.length }}件商品 合计：
              <span class="price">{{ order.totalPoints }}</span> 积分
            </div>
            <div class="order-actions">
              <van-button
                v-if="order.status === '待付款'"
                size="small"
                type="primary"
                @click="payOrder(order.id)"
              >去支付</van-button>
              <van-button
                v-if="order.status === '待收货' || order.status === '已发货'"
                size="small"
                type="primary"
                @click="confirmOrder(order.id)"
              >确认收货</van-button>
              <van-button
                v-if="order.status === '待付款' || order.status === '待发货'"
                size="small"
                plain
                @click="cancelOrder(order.id)"
              >取消订单</van-button>
              <van-button size="small" @click="goToOrderDetail(order.id)">查看详情</van-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showDialog, showSuccessToast } from 'vant'
import PageHeader from '@/components/PageHeader.vue'
import { useUserStore } from '@/stores/user'
import {
  getOrderList,
  confirmOrder as confirmOrderApi,
  cancelOrder as cancelOrderApi,
  payOrder as payOrderApi,
} from '@/api/order'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(true)
const activeTab = ref('all')
const orderList = ref<any[]>([])

// 获取订单列表
const fetchOrderList = async () => {
  loading.value = true
  try {
    const params: any = {
      page: 1,
      limit: 10,
      userId: userStore.userInfo?.id,
    }

    if (activeTab.value !== 'all') {
      // 处理特殊的tab名称，同时查询待收货和已发货状态
      if (activeTab.value === '待收货/已发货') {
        params.status = ['待收货', '已发货']
      } else {
        params.status = activeTab.value
      }
    }

    const res = await getOrderList(params)
    console.log('订单列表API响应:', res)
    if (res.code === 200 && res.data) {
      orderList.value = res.data.list || []
      console.log('订单列表数据:', orderList.value)

      // 调试每个订单的items
      orderList.value.forEach((order, index) => {
        console.log(
          `订单[${index}]:`,
          order.orderNo,
          '的items:',
          order.items || '无'
        )
      })
    } else {
      orderList.value = []
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    orderList.value = []
  } finally {
    loading.value = false
  }
}

// 跳转到订单详情
const goToOrderDetail = (id: number) => {
  router.push(`/order/${id}`)
}

// 确认收货
const confirmOrder = async (id: number) => {
  try {
    await showDialog({
      title: '确认收货',
      message: '确认已收到商品吗？',
      showCancelButton: true,
    })

    const res = await confirmOrderApi(id)
    if (res.code === 200) {
      showSuccessToast('确认收货成功')
      fetchOrderList()
    }
  } catch (error) {
    console.error('确认收货失败:', error)
  }
}

// 取消订单
const cancelOrder = async (id: number) => {
  try {
    await showDialog({
      title: '取消订单',
      message: '确认要取消该订单吗？',
      showCancelButton: true,
    })

    const res = await cancelOrderApi(id)
    if (res.code === 200) {
      showSuccessToast('取消订单成功')
      fetchOrderList()
    }
  } catch (error) {
    console.error('取消订单失败:', error)
  }
}

// 支付订单
const payOrder = async (id: number) => {
  try {
    await showDialog({
      title: '确认支付',
      message: '确认支付该订单吗？将从您的积分中扣除对应数量',
      showCancelButton: true,
    })

    const res = await payOrderApi(id)
    if (res.code === 200) {
      showSuccessToast('支付成功')
      fetchOrderList()
    } else {
      showDialog({
        title: '支付失败',
        message: res.message || '支付失败，请稍后再试',
      })
    }
  } catch (error) {
    console.error('支付订单失败:', error)
  }
}

// 监听标签页变化
watch(activeTab, () => {
  fetchOrderList()
})

onMounted(() => {
  fetchOrderList()
})
</script>

<style scoped lang="scss">
.order-container {
  min-height: 100vh;
  background-color: $background-color;
  padding-bottom: 50px;
}

.order-tabs {
  margin-bottom: $padding-xs;
}

.loading-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: $padding-xl 0;
}

.order-list {
  padding: $padding-xs;
}

.order-item {
  background-color: $white;
  border-radius: $border-radius-md;
  margin-bottom: $padding-md;
  overflow: hidden;

  .order-header {
    display: flex;
    justify-content: space-between;
    padding: $padding-md;
    border-bottom: 1px solid #f5f5f5;

    .order-no {
      font-size: $font-size-sm;
      color: $text-color-light;
    }

    .order-status {
      font-size: $font-size-sm;
      color: $primary-color;
      font-weight: 500;
    }
  }

  .order-content {
    padding: $padding-md;

    .product-item {
      display: flex;
      margin-bottom: $padding-sm;

      &:last-child {
        margin-bottom: 0;
      }

      .product-img {
        width: 60px;
        height: 60px;
        object-fit: cover;
        border-radius: $border-radius-sm;
        margin-right: $padding-md;
      }

      .product-info {
        flex: 1;
        position: relative;

        .product-name {
          font-size: $font-size-md;
          color: $text-color;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          margin-bottom: $padding-xs;
        }

        .product-price {
          font-size: $font-size-sm;
          color: $danger-color;
        }

        .product-quantity {
          position: absolute;
          right: 0;
          bottom: 0;
          font-size: $font-size-sm;
          color: $text-color-light;
        }
      }
    }
  }

  .order-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: $padding-md;
    border-top: 1px solid #f5f5f5;

    .order-total {
      font-size: $font-size-sm;
      color: $text-color;

      .price {
        font-size: $font-size-md;
        color: $danger-color;
        font-weight: 500;
      }
    }

    .order-actions {
      display: flex;
      gap: $padding-xs;
    }
  }
}
</style> 